package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.mallcai.bigdata.ladon.common.SessionThreadLocal;
import com.mallcai.bigdata.ladon.dpl.entity.report.QueryField;
import com.mallcai.bigdata.ladon.dpl.vo.DataType;
import com.mallcai.bigdata.ladon.dpl.vo.QueryFieldType;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 准备内部参数,内部参数以:开头
 * @author feixy
 * @version 1.0
 * @date 2019-07-19 21:06
 */
@Component
@Order(1500)
public class PrepareInnerParamHandler extends AbstractReportQueryPreHandler {

    private static final String USER_ID = ":USER_ID";

    @Override
    public void preInternal(ReportQueryContext context) {
        Map<String, Object> originalParams = context.getOriginalParams();
        Set<String> params = context.getInnerParam(ReportQueryConstants.KEY_ALL_PARAM_NAME);
        List<QueryField> innerFieldList = new ArrayList<>();
        if (params.contains(USER_ID)) {
            originalParams.put(USER_ID, SessionThreadLocal.getUserId());
            innerFieldList.add(createInnerQueryField(USER_ID,"用户ID",DataType.LONG.getCode(),String.valueOf(-1)));
        }
        context.putInnerParam(ReportQueryConstants.KEY_INNER_FIELD_LIST, innerFieldList);
    }

    private static QueryField createInnerQueryField(String name, String showName, String dateType, String defVal,
                                                    QueryFieldType... queryFieldTypes){
        QueryField queryField = new QueryField();
        queryField.setDataType(dateType);
        queryField.setQueryName(name);
        queryField.setShowName(showName);
        queryField.setValDefault(defVal);
        List<Integer> fieldTypeList = new ArrayList<>();
        fieldTypeList.add(QueryFieldType.INNER.getCode());
        for(QueryFieldType fieldType: queryFieldTypes){
            fieldTypeList.add(fieldType.getCode());
        }
        queryField.setType(QueryFieldType.merge(fieldTypeList));
        return queryField;
    }
}
